'use strict';
const db = uniCloud.database();
const collection = db.collection('students');

exports.main = async (event, context) => {
  const { action, name, password } = event;
  console.log('event : ', event);
  
  try {
    if (action === 'login') {
      const user = await collection.where({
        name:event.name,
        
        password:event.password
      }).get();
      
      if (user.affectedDocs < 1) {
        return {
          code: -1,
          msg: '用户名或者密码错误'
        };
      } else {
        const userInfo = user.data[0];
        delete userInfo.password; // 确保不返回密码
        
        return {
          code: 200,
          msg: '登录成功',
          data: userInfo
        };
      }
    } else if (action === 'register') {
      // 检查用户名是否已存在
      const existingUser = await collection.where({
        name
      }).get();
      
      if (existingUser.data.length > 0) {
        return {
          code: -5,
          msg: '用户名已存在'
        };
      }
      
      const registerResult = await collection.add({
        name,
        password,
        createTime: new Date()
      });
      
      if (registerResult.affectedDocs > 0) {
        return {
          code: 200,
          msg: '注册成功'
        };
      } else {
        return {
          code: -4,
          msg: '注册失败，请稍后再试'
        };
      }
    } else {
      return {
        code: -2,
        msg: '未知操作'
      };
    }
  } catch (error) {
    console.error('操作错误:', error);
    return {
      code: -3,
      msg: '服务器错误，请稍后再试'
    };
  }
};